package com.common.project.util;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


public class Util {

    static int[] DAYS = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    /**
     * parse request params
     * @param map a {@link Map} of the parameters of this request
     * @return
     */
	public static String parseRequestParams(Map<String,String[]> map) {
        StringBuilder builder = new StringBuilder();
        for (String key : map.keySet()) {
            builder.append("param").append(":").append(key).append(",").append("value").append(":");
            String[] values = (String[]) map.get(key);
            for (String value : values) {
                builder.append(value).append("\r\n");
            }
        }
        return builder.toString();
    }

    //封装Httpservelt 访问参数
    public static HashMap<String,Object> genHmParam(HttpServletRequest request) throws UnsupportedEncodingException{
        HashMap<String,Object> requestMap = new HashMap<String,Object>();
        Enumeration<String> params = request.getParameterNames();
        while(params.hasMoreElements()){
            String param = params.nextElement();
            String value = request.getParameter(param);
            if(value!=null){
                if(value.equals(new String(value.getBytes("iso8859-1"),"iso8859-1"))){
                    value=new String(value.getBytes("iso8859-1"),"utf-8");
                }
            }
            requestMap.put(param, value);
        }
        return requestMap;
    }

    //生成一个编码格式 yyyyMMddHHmmss+随机三位数
    public static String genCode(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String code = sdf.format(new Date())+(int)(Math.random()*1000);
        return code;
    }

    /**
     * @param date yyyy-MM-dd HH:mm:ss
     * @return
     */

    public static boolean isValidDate(String date) {
        try {
            int year = Integer.parseInt(date.substring(0, 4));
            if (year <= 0)
                return false;
            int month = Integer.parseInt(date.substring(5, 7));
            if (month <= 0 || month > 12)
                return false;
            int day = Integer.parseInt(date.substring(8, 10));
            if (day <= 0 || day > DAYS[month])
                return false;
            if (month == 2 && day == 29 && !isGregorianLeapYear(year)) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    public static final boolean isGregorianLeapYear(int year) {
        return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
    }
    public static boolean compareDate(Date d1,Date d2){
        if(d1.getTime()>d2.getTime()){
            return true;
        }else{
            return false;
        }
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }


    /**
     * MD5加密
     *
     * @param s
     * @return
     */
    public final static String MD5(String s) throws Exception {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            byte[] strTemp = s.getBytes();
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte b = md[i];
                str[k++] = hexDigits[b >> 4 & 0xf];
                str[k++] = hexDigits[b & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

}

